﻿using System;
using System.Collections.Generic;
using System.Text;
using PostSharp.Aspects.Dependencies;

namespace Arcana.Contract.Argument.Is
{
    /// <summary>
    /// Represents a contract that adheres to <b>Argument is in</b> semantic.
    /// </summary>
    [Serializable]
    [ProvideAspectRole(Roles.Contract)]
    [ProvideAspectRole(Roles.Method)]
    [ProvideAspectRole(Roles.Argument)]
    [ProvideAspectRole(Roles.Conditional)]
    [AspectRoleDependency(AspectDependencyAction.Commute, Roles.Conditional)]
    public sealed class InAttribute : ComparingContractBase
    {
        private System.Collections.IEnumerable _collection;

        /// <summary>
        /// Initializes a new instance of <b>Argument.Is.InAttribute</b>.
        /// </summary>
        /// <param name="argumentName">The argument to which this contract is applied.</param>
        /// <param name="collection">The collection of items which <i>argumentName</i> should be a member of.</param>
        /// <exception cref="System.ArgumentNullException"><i>argumentName</i> or <i>collection</i> is <b>null</b>.</exception>
        public InAttribute(string argumentName, object[] collection)
            : base(argumentName)
        {
            if (collection == null) throw new ArgumentNullException();
            _collection = collection;
        }

        /// <summary>
        /// Performs validation on the argument.
        /// </summary>
        /// <param name="argument">The argument that should be validated.</param>
        /// <returns><b>true</b> if <i>argument</i> is validated, otherwise <b>false</b>.</returns>
        protected override bool ValidateArgument(object argument)
        {
            foreach (var item in _collection)
            {
                if (Comparer.Compare(argument, item) == 0) return true;
            }
            return false;
        }
    }
}
